export const download = (blob, name) => {
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.download = name
    a.style.display = 'none'
    a.href = url
    document.body.appendChild(a)
    a.click()
    a.remove()
}
export const getBase64 = file => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result)
        reader.onerror = error => reject(error)
    })
}
export const cloneDeep = (obj, cache = []) => {
    function find(list, f) {
        return list.filter(f)[0]
    }
    if (obj === null || typeof obj !== 'object') {
        return obj
    }
    const hit = find(cache, c => c.original === obj)
    if (hit) {
        return hit.copy
    }
    const copy = Array.isArray(obj) ? [] : {}
    cache.push({
        original: obj,
        copy,
    })
    Object.keys(obj).forEach(key => {
        copy[key] = cloneDeep(obj[key], cache)
    })
    return copy
}
export const formatCascader = (tree, labelKey, valueKey, childrenKey) => {
    return tree.map(item => {
        let label = item[labelKey]
        let value = item[valueKey]
        let prevChildren = item[childrenKey]
        let children = []
        if (Array.isArray(prevChildren) && prevChildren.length > 0) {
            children = formatCascader(prevChildren, labelKey, valueKey, childrenKey)
        }
        if (children.length > 0) {
            return {
                value,
                label,
                children,
            }
        } else {
            return {
                value,
                label,
            }
        }
    })
}
export const formatTree = (tree, labelKey, valueKey, childrenKey) => {
    return tree.map(item => {
        let title = item[labelKey]
        let key = item[valueKey]
        let prevChildren = item[childrenKey]
        let children = []
        if (Array.isArray(prevChildren) && prevChildren.length > 0) {
            children = formatTree(prevChildren, labelKey, valueKey, childrenKey)
        }
        if (children.length > 0) {
            return {
                key,
                title,
                children,
            }
        } else {
            return {
                key,
                title,
            }
        }
    })
}
export const formatSelect = (arr, labelKey, valueKey) => {
    return arr.map(item => {
        let label = item[labelKey]
        let value = item[valueKey]
        return {
            value,
            label,
        }
    })
}

export const getAlarmClassName = ({ alertLevel }) => {
    let alarmClassName = {}
    switch (alertLevel) {
        case '零级报警':
            alarmClassName = {
                color: 'zero-alarm-color',
                bcolor: 'zero-alarm-bcolor',
            }
            break
        case '一级报警':
            alarmClassName = {
                color: 'one-alarm-color',
                bcolor: 'one-alarm-bcolor',
            }
            break
        case '二级报警':
            alarmClassName = {
                color: 'two-alarm-color',
                bcolor: 'two-alarm-bcolor',
            }
            break
        case '三级报警':
            alarmClassName = {
                color: 'three-alarm-color',
                bcolor: 'three-alarm-bcolor',
            }
            break
        default:
            alarmClassName = {
                color: 'other-alarm-color',
                bcolor: 'other-alarm-bcolor',
            }
    }
    return alarmClassName
}

export const getFinalPageNum = (total, pageNum = 1, pageSize = 10, delNum = 1) => {
    const restNum = total - pageSize * (pageNum - 1)
    let pageNumDiff = Math.floor((delNum - restNum) / pageSize) + 1
    pageNumDiff < 0 && (pageNumDiff = 0)
    pageNum = pageNum - pageNumDiff
    pageNum < 1 && (pageNum = 1)
    return pageNum
}

export const arrFindByKey = (arr, key, val) => {
    let result = {}
    if (Array.isArray(arr) && arr.length > 0) {
        for (let i = 0; i < arr.length; i++) {
            let item = arr[i]
            if (item[key] === val) {
                result = item
                break
            }
        }
    }
    return result
}

export const getColors = (randomColorKind = 20) => {
    const colors = []
    const getRandomColor = function () {
        let randomColor = '#'
        const arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
        for (let i = 0; i < 6; i++) {
            const num = parseInt(Math.random() * 16)
            randomColor += arr[num]
        }
        return randomColor
    }
    for (let i = 0; i < randomColorKind; i++) {
        colors.push(getRandomColor())
    }
    return ['#0084ff', '#5bc43a', '#2f3ced', '#ff7439', '#ffcc00'].concat(colors)
}
export const hexToRgba = (hex, opacity = 1) => {
    return (
        'rgba(' +
        parseInt('0x' + hex.slice(1, 3)) +
        ',' +
        parseInt('0x' + hex.slice(3, 5)) +
        ',' +
        parseInt('0x' + hex.slice(5, 7)) +
        ',' +
        opacity +
        ')'
    )
}

export const setColumnsEllipsis = columns => {
    return columns.map(column => {
        return Object.assign(
            { ...column },
            {
                ellipsis: true,
            },
        )
    })
}
export const getItemById = (data, id, idKey = 'id') => {
    let result
    function findSel(treeData) {
        treeData.forEach(el => {
            if (!result) {
                if (id === el[idKey]) {
                    result = el
                }
                if (el.children?.length) {
                    findSel(el.children)
                }
            }
        })
    }
    findSel(data)
    return result
}
export const getParentItemByChildId = (data, childId, idKey = 'id', pIdKey = 'parentId') => {
    return getItemById(data, (getItemById(data, childId, idKey) || {})[pIdKey], idKey)
}
export const getSelectedIds = (data, id, parentKey = 'parentId', key = 'id', childrenKey = 'children') => {
    // rootPId作用：根节点的pId设置为了一个值，但是找不到对应的以pId的值为id的节点， 也就是说根节点的pId是无效的，不能被push进来(过滤脏数据)
    // 找到第一级的pId(rootPId)
    const rootPIds = data.map(item => item[parentKey])
    const selResult = []
    function findSel(data, id) {
        let isFind = false
        for (const i of data) {
            if (isFind) {
                break
            }
            if (i[key] !== id) {
                if (undefined !== i[childrenKey] && i[childrenKey] !== null) {
                    if (i[parentKey] && !rootPIds.includes(i[parentKey])) {
                        selResult.push(i[parentKey])
                    }
                    isFind = findSel(i[childrenKey], id)
                }
            } else {
                if (i[parentKey] && !rootPIds.includes(i[parentKey])) {
                    selResult.push(i[parentKey])
                }
                selResult.push(id)
                isFind = true
            }
        }
        if (!isFind) {
            selResult.pop()
        }
        return isFind
    }
    findSel(data, id)
    return selResult
}
// _parID 父节点标识.标识它是父节点的值(数据是乱的,给出pid的值找不到对应id,则传空)
export const getTreeData = (data, idKey = 'id', parentIdKey = 'parentId', childrenKey = 'children', _parID) => {
    if (!data || data.length === 0) {
        return []
    }
    if (_parID === undefined || _parID === null || _parID === '') {
        // 找根数据（根节点的pid未知）
        const disParentCode = []
        // 遍历出所有的上级ID
        for (const item of data) {
            const parID = item[parentIdKey]
            if (disParentCode.indexOf(parID) > -1) {
                continue
            }
            disParentCode.push(parID)
        }
        // 遍历出所有的ID
        const disCode = []
        for (const item of data) {
            const funID = item[idKey]
            disCode.push(funID)
        }
        const notExisted = []
        for (const item of disParentCode) {
            if (disCode.indexOf(item) === -1) {
                notExisted.push(item)
            }
        }
        const resultList = []
        for (const item of data) {
            const parID = item[parentIdKey]
            if (notExisted.indexOf(parID) > -1) {
                resultList.push(item)
            }
        }
        // 查找下级
        for (const item of resultList) {
            const funID = item[idKey]
            const temp = getTreeData(data, idKey, parentIdKey, childrenKey, funID)
            if (temp.length > 0) {
                item[childrenKey] = temp
            }
        }
        return resultList
    } else {
        // 根节点的pid已知
        const resultList = []
        for (const item of data) {
            const parID = item[parentIdKey]
            if (parID !== null && parID === _parID) {
                resultList.push(item)
            }
        }
        // 查找下级
        for (const item of resultList) {
            const funID = item[idKey]
            const temp = getTreeData(data, idKey, parentIdKey, childrenKey, funID)
            if (temp.length > 0) {
                item[childrenKey] = temp
            }
        }
        return resultList
    }
}
// 从小到大 空排在最后
export const sortMinToNull = (list, sortKey = 'sort') => {
    list.sort((a, b) => {
        return (
            (b[sortKey] !== '' && b[sortKey] !== null && b[sortKey] !== undefined) -
                (a[sortKey] !== '' && a[sortKey] !== null && a[sortKey] !== undefined) || a[sortKey] - b[sortKey]
        )
    })
    return list
}
export const optionsIsExitId = (options, id) => {
    let isFind = false
    function find(data) {
        data.forEach(option => {
            if (option.id === id) {
                isFind = true
            }
            if (!isFind) {
                if (option.children && option.children.length) {
                    find(option.children)
                }
            }
        })
    }
    find(options)
    return isFind
}
// 禁用/启用
export const disabledOptionsItem = (options, disabledIds = []) => {
    const find = data => {
        data.forEach(item => {
            if (disabledIds.includes(item.id)) {
                item.disabled = true
            } else {
                item.disabled = false
            }
            if (item.children?.length) {
                find(item.children)
            }
        })
    }
    find(options)
    return options
}
export const getEffectIds = (options, ids) => {
    const effectIds = []
    function find(data) {
        data.forEach(option => {
            if (ids.includes(option.id)) {
                effectIds.push(option.id)
            }
            if (option.children && option.children.length) {
                find(option.children)
            }
        })
    }
    find(options)
    return effectIds
}
export const getParentKey = (tree, id, idKey = 'id', childrenKey = 'children') => {
    let parentKey
    for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        if (node[childrenKey]) {
            if (node[childrenKey].some(item => item[idKey] === id)) {
                parentKey = node[idKey]
            } else if (getParentKey(node[childrenKey], id)) {
                parentKey = getParentKey(node[childrenKey], id)
            }
        }
    }
    return parentKey
}
export const getPIds = (data, id, parentKey = 'parentId', key = 'id', childrenKey = 'children') => {
    return getSelectedIds(data, id, parentKey, key, childrenKey).filter(item => item !== id)
}
export const generateList = (data, idKey = 'id', titleKey = 'name', childrenKey = 'children') => {
    const dataList = []
    function findData(options) {
        for (let i = 0; i < options.length; i++) {
            const node = options[i]
            const key = node[idKey]
            dataList.push({ key, title: options[i][titleKey] })
            if (node[childrenKey]) {
                findData(node[childrenKey])
            }
        }
    }
    findData(data)
    return dataList
}
export function scorePassword(pass) {
    let score = 0
    if (!pass) {
        return score
    }
    // award every unique letter until 5 repetitions
    const letters = {}
    for (let i = 0; i < pass.length; i++) {
        letters[pass[i]] = (letters[pass[i]] || 0) + 1
        score += 5.0 / letters[pass[i]]
    }

    // bonus points for mixing it up
    const variations = {
        digits: /\d/.test(pass),
        lower: /[a-z]/.test(pass),
        upper: /[A-Z]/.test(pass),
        nonWords: /\W/.test(pass),
    }

    let variationCount = 0
    for (var check in variations) {
        variationCount += variations[check] === true ? 1 : 0
    }
    score += (variationCount - 1) * 10

    return parseInt(score)
}
